import { Inject, Post, Get, Body } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { AutomationPipelineEntity } from '../../entity/pipeline'; 
import { AutomationConditionEntity } from '../../entity/condition';
import { AutomationTaskEntity } from '../../entity/task';
import { AutomationPipelineService } from '../../service/app/pipeline';

/**
 * 自动化流水线
 */
@CoolController({
  api: ['page'],
  entity: AutomationPipelineEntity,
  service: AutomationPipelineService,
  pageQueryOp: {
    keyWordLikeFields: ['a.name'],
    fieldEq: ['a.status'],
    fieldLike: [],
    where: async (ctx) => {
      const { createTime, triggerType } = ctx.request.body;
      const conditions = [];
      if (createTime && createTime.length === 2) {
        conditions.push([`a.createTime BETWEEN '${createTime[0]}' AND '${createTime[1]}'`]);
      }
      if (triggerType && triggerType.length > 0) {
        conditions.push([`a.triggerType IN (${triggerType.join(',')})`]);
      }
      return conditions;
    },
    select: ['a.*', 'conditions', 'tasks'],
    join: [
      {
        entity: AutomationConditionEntity,
        alias: 'b',
        condition: 'a.id = b.pipelineId',
        type: 'leftJoin',
      },
      {
        entity: AutomationTaskEntity,
        alias: 'c',
        condition: 'a.id = c.pipelineId',
        type: 'leftJoin',
      },
    ],
    extend: async (find) => {
      find.groupBy('a.id');
    },
  },
})
export class AdminAutomationPipelineController extends BaseController {
  @Inject()
  automationPipelineService: AutomationPipelineService;

  /**
   * 新增流水线
   * @param params
   * @returns
   */
  @Post('/addPipeline', { summary: '新增流水线' })
  async addPipeline(@Body() params) {
    return this.ok(await this.automationPipelineService.addPipeline(params));
  }

  /**
   * 更新流水线
   * @param params
   * @returns
   */
  @Post('/updatePipeline', { summary: '更新流水线' })
  async updatePipeline(@Body() params) {
    return this.ok(await this.automationPipelineService.updatePipeline(params));
  }

  /**
   * 删除流水线
   * @param ids
   * @returns
   */
  @Post('/deletePipeline', { summary: '删除流水线' })
  async deletePipeline(@Body('ids') ids: number[]) {
    return this.ok(await this.automationPipelineService.deletePipeline(ids));
  }

  /**
   * 流水线详情
   * @param id
   * @returns
   */
  @Get('/pipelineDetail', { summary: '流水线详情' })
  async pipelineDetail(@Body('id') id: number) {
    return this.ok(await this.automationPipelineService.pipelineDetail(id));
  }
}